package com.caocaog.market.toccpt.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caocaog.market.toccpt.ccptmodel.*;
import com.caocaog.market.toccpt.jedis.CcptJedisConfig;
import com.caocaog.market.toccpt.jiguang.JiGuangPushUtil;
import com.caocaog.market.toccpt.mapper.CcptMapper;
import com.caocaog.market.toccpt.mapper.MarketOrderMapper;
import com.caocaog.market.toccpt.marketmodel.*;
import com.caocaog.market.toccpt.service.ToCcptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.toccpt.service.impl
 * @ClassName ToCcptServiceImpl.java
 * @createTime 2021年12月25日 09:43:00
 * @Description TODO
 */
@Service("toCcptService")
@Slf4j
public class ToCcptServiceImpl implements ToCcptService {

    @Autowired
    private MarketOrderMapper marketOrderMapper;
    @Autowired
    private CcptMapper ccptMapper ;
    // 常量
    private static final String ERROR = "error";
    private static final String SUCCESS = "success";
    private static final String ACTUAL_CCPT_PRICE = "actualCcptPrice";
    // 获取线上redis的连接
    private final Jedis ccJedis = new CcptJedisConfig().getJedis();
    // 获取线上rabbitmq的连接
//    private final ConnectionFactory factory = RabbitMQUtil.getRabbitMQConnectionFactory();
    @Override
    public Result dealOrder(String payNo) {
        // payNo 是交易流水号,不能为空
        Result result = new Result();

        if(StringUtils.isBlank(payNo)){
            // 订单查询失败
            result.error500("付款单号不能为空");
            return result;
        }
        /**
         * 一、根据付款单号先从  曹操来了  查询出商城订单
         */
        log.info("一、根据付款单号先从  曹操来了  查询出商城订单");
        OrderBaseInfo orderBaseInfo = findMarketOrder(payNo);
        String marketOrderId = orderBaseInfo.getOrderId();
        if(null == orderBaseInfo){
            result.error500("根据订单号没有查询到需要向曹操跑腿发送的订单！");
            return result;
        }
        JSONObject reltObj = new JSONObject();
        reltObj.putOpt("marketOrderNo",orderBaseInfo.getOrderNo());
        reltObj.putOpt("marketOrderId",orderBaseInfo.getOrderId());
        reltObj.putOpt("marketPayNo",payNo);
        result.setResult(reltObj);
        /**
         * 查询该订单是否已向跑腿甩单；
         *      只有订单状态为：1：支付成功待接单，2：已接单，3：骑士到店，4：已取货/配送中，5：已送达，6：订单完成
         *      时才会提示；
         *
         *      如果跑腿中订单状态为：21：用户取消订单，22：代理商取消订单，23：总后台取消订单     时，可以再次向曹操跑腿发单
         */
        log.info("查询该订单是否已向跑腿甩单；");
        int num = ccptMapper.findForThirdPartyNo(orderBaseInfo.getOrderNo());
        if(num>0){
            result.error500("订单号"+orderBaseInfo.getOrderNo()+",已向曹操跑腿发单，请勿重复向跑腿发单！");
            return result;
        }
        /**
         *  二、检测该订单所属的门店有没有绑定跑腿账号
         */
        log.info("二、检测该订单所属的门店有没有绑定跑腿账号");
        int nu = checkBindCcptMember(orderBaseInfo);
        if(nu==0){
            result.error500("请先绑定跑腿账号！");
            return result;
        }
        /**
         * 根据店铺id查询曹操来了的店铺地址
         */
        log.info("根据店铺id查询曹操来了的店铺地址");
        ShopInfo shopInfo = marketOrderMapper.findShopByShopId(orderBaseInfo.getShopId());
        if(null == shopInfo){
            result.error500("没有查询到曹操来了的门店信息");
            return result;
        }
        /**
         * 三、查询曹操来了配送信息
         */
        log.info("三、查询曹操来了配送信息");
        OrderDeliveryInfo marketDeliveryInfo = findMarketDelivery(marketOrderId);
        if(null==marketDeliveryInfo){
            result.error500("未查询到该订单的配送信息！");
            return result;
        }
        /**
         * 四、根据曹操来了商城订单查询该订单归属于“曹操跑腿”系统中的哪个代理商
         *      返回曹操跑腿系统中的代理商id
         */
        log.info("四、根据曹操来了商城订单查询该订单归属于“曹操跑腿”系统中的哪个代理商");
        int agentId = findSitecOrrespondingAgentId(orderBaseInfo.getSiteId());
        if(agentId==0){
            result.error500("未查询到该订单所属分站中对应的曹操跑腿系统中的代理商id！");
            return result;
        }

        GetPriceModel priceModel = new GetPriceModel();
        // 这里的距离的单位是km，而且带有两位小数
        String distance = marketDeliveryInfo.getDeliveryDistance();
        if(StringUtils.isBlank(distance)){
            result.error500("订单距离不能为空");
            return result;
        }
        BigDecimal distanceDecimal = new BigDecimal(distance);
        if(distanceDecimal.compareTo(new BigDecimal(0))<1){
            result.error500("订单距离不能小于或等于0");
            return result;
        }
        // 订单距离乘1000转换成米
        priceModel.setDis((distanceDecimal.multiply(new BigDecimal(1000))).intValue());
        // 订单类型：帮我送
        priceModel.setOrderType(1);
        /**
         *  五、订单中商品的重量
         *     从商品规格里面取，这里注意一下：一个商品一个重量
         *     1、从该订单中取出该订单中的所有商品
         *     2、再从每个商品中取出每个商品下单时的规格信息
         *     3、从规格信息中取出每个商品的重量，把所有商品的重量加起来算出该订单的总重量
         */
        log.info("五、订单中商品的重量");
        List<OrderLineInfo> lineInfos = marketOrderMapper.findOrderLineByOrderId(marketOrderId);
        if(null==lineInfos || lineInfos.size()<1){
            result.error500("根据订单id没有查询到属于该订单的商品");
            return result;
        }
        Map<String,String> twMap = findMarketTotalWeight(lineInfos);
        if(twMap.containsKey(ERROR)){
            result.error500(twMap.get(ERROR));
            return result;
        }
        priceModel.setWeight(Integer.parseInt(twMap.get(SUCCESS)));
        priceModel.setAgentId(agentId);
        int ptMemberId = orderBaseInfo.getPtId();
        if(ptMemberId<1){
            result.error500("请检查门店是否绑定了曹操跑腿的发单账号");
            return result;
        }
        priceModel.setMemberId(ptMemberId);
        /**
         * 六、计算商家需要支付的跑腿费用
         *      key为ERROR时，表示有错误信息
         *      key为SUCCESS时，表示跑腿费用计算正常
         */
        log.info("六、计算商家需要支付的跑腿费用");
        priceModel.setDispatchingType(1);
        // 预付款
        priceModel.setImprest(new BigDecimal(0));
        // 客户加价
        priceModel.setRaisePrice(new BigDecimal(0));
        Map<String,String> ccptMoneyMap = getPriceAsync(priceModel);
        if(ccptMoneyMap.containsKey(ERROR)){
            result.error500(ccptMoneyMap.get(ERROR));
            return result;
        }
        // 实际向跑腿支付的跑腿费：ccptMoneyMap.get("pay")
        String ccptMoney = ccptMoneyMap.get(SUCCESS);
        log.info("-----160行 ccptMoney "+ccptMoney);
        // {"agentId":252,"timePrice":"0","price":8.8,"payPrice":"8.8","priceData":"[{\"price\":\"8.80\",\"name\":\"订单金额\"},{\"price\":\"7.80\",\"name\":\"起步价\"},{\"price\":\"1.00\",\"name\":\"超公里计价\"},{\"price\":\"0.00\",\"name\":\"优惠金额\"},{\"price\":\"8.80\",\"name\":\"支付金额\"}]","priceId":"dc8f47d3995208dddb72f75c0bb4d8f5","specialPrice":"0"}
        /**
         * 七、构建插入跑腿订单表的数据（map）
         */
        log.info("七、构建插入跑腿订单表的数据（map）");
        Map<String,String> params = createOrderModel(ccptMoneyMap);
        params.put("memberId",String.valueOf(ptMemberId));
        params.put("agentId",String.valueOf(agentId));
        params.put("marketOrderNo",orderBaseInfo.getOrderNo());
        params.put("remark",orderBaseInfo.getRemark());
        params.put("orderDis",String.valueOf(priceModel.getDis()));
        params.put("orderType",String.valueOf(priceModel.getOrderType()));
        //params.put("goodsWeight",twMap.get("goods_totalWeight"));
        params.put("goodsWeight",twMap.get("success"));
        params.put("imprest",String.valueOf(priceModel.getImprest()));
        params.put("raisePrice",String.valueOf(priceModel.getRaisePrice()));
        params.put("receiptAddr",marketDeliveryInfo.getDeliveryAddress());
//        params.put("receiptAddrAoi",marketDeliveryInfo.getDeliveryLocation());
        params.put("receiptAddrAoi",marketDeliveryInfo.getDeliveryAddress());
        params.put("receiptAddrHouse","");
        params.put("receiptLat",marketDeliveryInfo.getDeliveryLat());
        params.put("receiptLon",marketDeliveryInfo.getDeliveryLng());
        params.put("receiptMobile",marketDeliveryInfo.getDeliveryMobile());
        params.put("receiptName",marketDeliveryInfo.getDeliveryName());
        params.put("sendLat",shopInfo.getLat());
        params.put("sendLon",shopInfo.getLng());
        params.put("sendMobile",orderBaseInfo.getMerchantPhone());
        params.put("sendName",shopInfo.getName());
        params.put("sendAddr",shopInfo.getAddressText());
        params.put("sendAddrAoi",shopInfo.getAddressText());
        params.put("disAmount",String.valueOf(new BigDecimal("0.00")));

        /**
         * 八、写入跑腿数据库（即：向cc_order表中插入数据）
         */
        log.info("八、写入跑腿数据库（即：向cc_order表中插入数据）");
        Map<String,String> insertCcorderReMap =  createCcOrder(orderBaseInfo,params);
        if(insertCcorderReMap.containsKey(ERROR)){
            result.error500(insertCcorderReMap.get(ERROR));
            return result;
        }
        int ccptOrderId = Integer.parseInt(insertCcorderReMap.get("ccOrderId"));
        /**
         * 九、根据跑腿的订单数据id查询cc_order表中的数据记录
         */
        log.info("九、根据跑腿的订单数据id查询cc_order表中的数据记录");
        CcOrder order  = findCcptOrderById(ccptOrderId);
        if(null==order){
            result.error500("没有查询到跑腿订单的数据，请您核对！");
            return result;
        }
        /**
         * 十、检测是否使用了，如果有就更新优惠券，如果没有就不更新
         */
        log.info("十、检测是否使用了，如果有就更新优惠券，如果没有就不更新");
        if(order.getCouponSid()>0){
            // 使用了优惠券，添加优惠券的核销记录
            Map<String, String> couponMap = new HashMap<String,String>();
            couponMap.put("couponId",String.valueOf(order.getCouponSid()));
            couponMap.put("couponAmount",String.valueOf(order.getDiscounts()));
            couponMap.put("agentId",String.valueOf(order.getAgentSid()));
            couponMap.put("couponMoney",String.valueOf(order.getDiscounts()));
            couponMap.put("ccOrderNo",order.getOrderNo());
            couponMap.put("disCounts",String.valueOf(order.getDiscounts()));
            couponMap.put("memberId",String.valueOf(order.getMemberSid()));
            couponMap.put("ccOrderId",String.valueOf(order.getSid()));
            updateCounpon(couponMap);
        }
        /**
         * 十、新订单推送
         */
        log.info("十、新订单推送");
        Map<String, String> pushMap = newOrderPush(order);
        if(pushMap.containsKey(SUCCESS)){
            result.success("向跑腿甩单成功！");
            result.setResult(null);
            reltObj.putOpt("ccptOrderSid",order.getSid());
            reltObj.putOpt("ccptOrderMemberSid",order.getMemberSid());
            reltObj.putOpt("ccptOrderNo",order.getOrderNo());
            log.info("向曹操跑腿甩单成功，返回到曹操来了系统的内容："+reltObj.toString());
            result.setResult(reltObj);
        }else{
            result.error500("向跑腿甩单失败！");
        }
        return result;
    }

    @Override
    public Result customerCancelOrder(int ccptOrderId) {
        /**
         * 跑腿系统中的订单状态 1：支付成功待接单，2：已接单，3：骑士到店，4：已取货/配送中，5：已送达，6：订单完成，
         *      下面的这三个状态不用管
         *      21：用户取消订单，22：代理商取消订单，23：总后台取消订单
         */
        Result result = new Result();
        String refundNo = "";//退款单号
        int cancelStatus = 21;
        CcOrder order = findCcptOrderForCancelByOrderId(ccptOrderId);
        if (null==order){
            // 订单信息异常，
            result.error500("无法取消订单！");
            return result;
        }
        log.info("ToCcptServiceImpl.java----287行    订单状态：" + order.getOrderStatus() + " pay_status：" + order.getPayStatus() + " pay_way：" + order.getPayWay()
                + " pay_amount：" + order.getPayAmount() + " third_party_no：" + order.getThirdPartyNo() + " member_sid：" + order.getMemberSid()
                + " coupon_sid：" + order.getCouponSid() + "staff_sid：" + order.getStaffSid() + " agent_sid：" + order.getAgentSid());
        int ccptOrderStatus = order.getOrderStatus();
        if (ccptOrderStatus > 4){
            String str = "已送达无法取消，如有其他需求请联系商家！";
            if(ccptOrderStatus==21 || ccptOrderStatus==22 || ccptOrderStatus==23){
                str = "曹操跑腿订单已取消，请勿重复操作；如有其他需求请联系商家！";
            }
            result.error500(str);
            return result;
        }
        boolean isok = false, isall = false, issending = false;
        BigDecimal rmoney = order.getPayAmount();
        String url = order.getCallbackUrl(), tno = order.getThirdPartyNo();
        // 更改订单状态
        int i = updateOrderForCancel(cancelStatus, DateUtils.getDate(),order.getSid(),order.getOrderStatus());
        isall = true;
        if(i>0){
            OrderLog orderLog = new OrderLog();
            //添加订单操作日志
            orderLog.setAfterStatus((byte)cancelStatus);
            orderLog.setBeforeStatus(order.getOrderStatus());
            orderLog.setCreateDate(DateUtils.getDate());
            orderLog.setOrderSid(order.getSid());
            orderLog.setRemark("曹操来了取消订单，曹操来了订单号:" + order.getThirdPartyNo());
            orderLog.setSid(order.getStaffSid());
            int orderLogNum = insertCcOrderLog(orderLog);
            //移除redis中骑士进行中的订单
            if(isall){
                //移除redis中该订单数据
                ccJedis.select(25);
                String keyPattern = "staffNewOrder:*-"+order.getSid();
                Set<String> setkeys = ccJedis.keys(keyPattern);
                for (String key:setkeys){
                    if(StringUtils.isNotBlank(key)){
                        ccJedis.del(key);
                    }
                }
                //移除newOrder
                ccJedis.select(25);
                ccJedis.hdel("newOrder", String.valueOf(order.getSid()));
                ccJedis.select(25);
                ccJedis.del("newOrderInfo:"+order.getSid());
                ccJedis.select(24);
                ccJedis.del("sendingOrder:"+order.getStaffSid()+"-"+order.getSid());
                //移除redis中预约单提醒——————目前没有做预约单，所以这里不用考虑移除redis中的预约单提醒的内容

                //更改订单修正数据状态——————目前订单修正数据也是没有做的，可以不用关注，但是因为只是根据订单id改变一个状态，所以写上也无所谓
                updateOrderAmend(order.getSid());
                /**
                 * 余额退款
                 */
                //添加记录并更新余额
                Result rt = addUserRecord((byte)7,order.getMemberSid(),rmoney,order.getOrderNo(),"订单退款(余额)");
                if(!rt.isSuccess()){
                    result.error500(rt.getMessage());
                    return result;
                }else{
                    isok = true;
                }
                if(isok){
                    // 优惠券退回
                    int couponid = order.getCouponSid();
                    if(couponid>0){
                        log.info("ToCcptServiceImpl.java--347行-----优惠券退回，优惠券id="+couponid);
                        ccptMapper.couponThById(couponid);
                    }
                }
                //通知骑士订单取消
                if (order.getStaffSid() > 0){
                    ccJedis.select(23);
                    Object object =ccJedis.hget("staffConfig", String.valueOf(order.getStaffSid()));
                    if(null!=object){
                        String config = object.toString();
                        log.info("ToCcptServiceImpl.java----350行--- "+config);
                        if(StringUtils.isNotBlank(config)){
                            StaffConfigModel staffConfigModel = JSONUtil.toBean(config,StaffConfigModel.class);
                            log.info("NowTakeOrder：" + staffConfigModel.getNowTakeOrder());
                            int orderNum = staffConfigModel.getNowTakeOrder()-1;
                            staffConfigModel.setNowTakeOrder(orderNum) ;
                            log.info( "NowTakeOrder：" + staffConfigModel.getNowTakeOrder());
                            ccJedis.select(23);
                            ccJedis.hset("staffConfig", String.valueOf(order.getStaffSid()), JSONUtil.toJsonStr(staffConfigModel));
                        }
                    }
                    // 向骑士推送订单取消  消息
                    cancelPush(order.getSid(),order.getStaffSid());
                }
                //是否有折扣金额
                if(bigDecimalCompare(order.getDisAmount(),new BigDecimal(0))>0){
                    BigDecimal disAmount = order.getDisAmount();
                    log.info("ToCcptServiceImpl.java--374行----取消订单时处理折扣金额返还"+disAmount.toString()+" 订单id："+order.getSid());
                    //获取当前代理商资金池余额
                    BigDecimal agentPoolingBalance = ccptMapper.findAgentCashPoolingBalance(order.getAgentSid());
                    BigDecimal nowBalance = agentPoolingBalance.add(disAmount);
                    int ci = ccptMapper.updateAgentCashPoolingBalance(nowBalance,order.getAgentSid(),agentPoolingBalance);
                    if(ci>0){
                        // 插入资金池流水记录
                        ccptMapper.insertAgentPoolingRecord(order.getAgentSid(),order.getOrderNo(),agentPoolingBalance,
                                nowBalance,disAmount,27,"取消订单折扣金额返还",DateUtils.getDate());
                    }else{
                        agentPoolingBalance = ccptMapper.findAgentCashPoolingBalance(order.getAgentSid());
                        nowBalance = agentPoolingBalance.add(disAmount);
                        ci = ccptMapper.updateAgentCashPoolingBalance(nowBalance,order.getAgentSid(),agentPoolingBalance);
                        if(ci<=0){
                            agentPoolingBalance = ccptMapper.findAgentCashPoolingBalance(order.getAgentSid());
                            nowBalance = agentPoolingBalance.add(disAmount);
                            ci = ccptMapper.updateAgentCashPoolingBalance(nowBalance,order.getAgentSid(),agentPoolingBalance);
                            if (ci <= 0){
                                log.info("ToCcptServiceImpl.java----392----订单取消折扣金额返还资金池超过3次失败，订单id："+order.getSid()+" agentId:"+order.getAgentSid());
                                ccJedis.select(20);
                                ccJedis.hset("errCashBalanceCancel",order.getAgentSid()+"-"+order.getSid(),"订单取消折扣金额返还资金池超过3次失败，订单id："+order.getSid()+" agentId:"+order.getAgentSid()+" 金额："+disAmount);
                            }
                        }
                    }
                }
            }
            result.success("订单取消成功！");
        }else{
            log.info("------ToCcptServiceImpl.java  ----402行，订单取消失败，失败原因：更新cc_order的订单状态时失败");
            result.error500("订单取消失败！");
        }
        return result;
    }
    /// <summary>
    /// 取消订单推送
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="staffId"></param>
    /// <param name="logCode"></param>
    private void cancelPush(int orderId, int staffId){
        // 根据骑士id查询骑士别名

        Map<String, String> extras = new HashMap<String,String>();
        extras.put("code",String.valueOf(3));
        extras.put("data",String.valueOf(orderId));
        extras.put("title","曹操跑腿");
        extras.put("builder_id",String.valueOf(1));
        extras.put("large_icon","http://img.ccpt.xyz/app/875c2ca7-d83c-45a7-9a6f-e8ace57d3e99.jpg");
        extras.put("time_to_live",String.valueOf(60));
        extras.put("apns_production",String.valueOf(true));
        JiGuangPushUtil.jpushAll(extras,"订单取消 ",new String[]{"ccptstaff" + staffId});
    }
    private Result addUserRecord(byte changeType, int orgId, BigDecimal changeCount, String serNo, String remark){
        Result relt = new Result();
        try{
            //是否需要添加平台流水
            boolean addrecord = false;
            //客户账户变更，需要正数
            if (bigDecimalCompare(changeCount,new BigDecimal(0))<1){
                log.info("不能对客户进行扣款操作 return");
                relt.error500("客户账户变更，需要正数");
                return relt;
            }
            //获取发单客户当前余额
            Map<String,Object> memberMap =  ccptMapper.findMemberForBalance(orgId);
            BigDecimal after = (BigDecimal) memberMap.get("balance");
            BigDecimal before = after;
            after = after.add(changeCount);
            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setAfterChange(after);
            userAccountRecord.setBeforeChange(before);
            userAccountRecord.setChangeType(changeType);
            userAccountRecord.setChangeValue(changeCount);
            userAccountRecord.setCreateDate(DateUtils.getDate());
            userAccountRecord.setRemark(remark);
            userAccountRecord.setUserSid(orgId);
            userAccountRecord.setSerNo(serNo);
            int j = ccptMapper.insertUserAccountRecord(userAccountRecord);
            if(j>0){
                //记录添加成功，是否需要更新余额
                if (bigDecimalCompare(after,before)!=0){
                    String bal = after.toString();
                    //更新用户余额
                   int up = ccptMapper.updateBalanceBySid(bal,orgId);
                   if(up>0){
                       // 用户余额更新成功
                       addrecord = true;
                   }else{
                       // 用户余额更新失败
                       log.info("用户余额更新失败，用户id= "+orgId);
                       addrecord = false;
                       // 这里需要删除上面添加的UserAccountRecord记录
                       relt.error500("用户余额更新失败");
                       return relt;
                   }
                }
            }else{
                //添加用户账户记录失败
                log.info("添加用户账户记录失败 end");
                relt.error500("添加用户账户记录失败");
                return relt;
            }
        }catch (Exception e){
            relt.error500("添加用户记录失败以及更新发单用户余额失败！");
        }
        relt.success("添加用户记录以及更新发单用户余额成功！");
        return relt;
    }
    @Override
    public int merchantCancelOrder(String marketOrderNo) {
        return 0;
    }

    /**
     * 对外提供的接口，根据曹操跑腿系统中的订单id查询订单
     */
    @Override
    public CcOrder findCcOrderBySid(int orderSid) {
        return findCcptOrderById(orderSid);
    }
    /**
     * 用户取消订单时根据订单id查询订单信息
     * 参数：订单id
     */
    @Override
    public CcOrder findCcptOrderForCancelByOrderId(int orderId) {
        return ccptMapper.findCcptOrderById(orderId);
//        return ccptMapper.findCcptOrderForCancelByOrderId(orderId);
    }
    /**
     * 取消曹操跑腿订单，
     *   参数：
     *      cancelStatus   取消状态
     *      cancelTime 取消时间
     *      orderId  曹操跑腿订单id
     *      orderStatus  订单原始状态
     */
    @Override
    public int updateOrderForCancel(int cancelStatus, Date cancelTime, int orderId, int orderStatus) {

        return ccptMapper.updateOrderForCancel(cancelStatus,cancelTime,orderId,orderStatus);
    }
    /**
     * 存订单取消的日志记录
     */
    @Override
    public int insertCcOrderLog(OrderLog orderLog) {

        return ccptMapper.insertCcOrderLog(orderLog);
    }
    /**
     * 更改订单修正数据的状态
     */
    @Override
    public int updateOrderAmend(int orderId) {

        return ccptMapper.updateOrderAmend(orderId);
    }

    /**
     * 一、根据订单号先从  曹操来了  查询出商城订单
     */
    private OrderBaseInfo findMarketOrder(String payNo){
        OrderBaseInfo marketOrderBaseInfo = marketOrderMapper.findOrderBaseBypayNo(payNo);
        if(null == marketOrderBaseInfo){
            return null;
        }
        return marketOrderBaseInfo;
    }
    /**
     * 二、检测该订单所属的门店有没有绑定跑腿账号
     */
    private int checkBindCcptMember(OrderBaseInfo orderBaseInfo ){
        int bindPtId = orderBaseInfo.getPtId();
        String bindPtLoginName = orderBaseInfo.getPtLoginName();
        if(bindPtId<1 || StringUtils.isBlank(bindPtLoginName)){
            return 0;
        }
        return 1;
    }
    /**
     * 三、查询配送信息
     */
    private OrderDeliveryInfo findMarketDelivery(String marketOrderId){
        return marketOrderMapper.findOrderDeliveryByOrderId(marketOrderId);
    }
    /**
     * 四、根据分站id去分站表中mk_site_basic表中查询该分站对应的曹操跑腿系统中的代理商id
     */
    private int findSitecOrrespondingAgentId(String siteId){
        String agentId = marketOrderMapper.findSitecOrrespondingAgentId(siteId);

        return StringUtils.isBlank(agentId) ? 0 : Integer.parseInt(agentId);
    }

    /**
     * 五、计算曹操来了商城订单的总重量
     *      返回值中的key为error的表示有错误信息；key为success的表示获取商品的重量类型，可以直接用于后续的计算
     *   注意：当返回的map中含success时，值为：1或2或3；这三个才是正确信息
     *      1：商品总重量的类型【即：商品总重量在25公斤以内（包含25公斤）】
     *      2：商品总重量的类型【即：商品总重量在25-50公斤（包含50公斤）】
     *      3：商品总重量的类型【即：商品总重量在50公斤以上】
     */
    private Map<String,String> findMarketTotalWeight(List<OrderLineInfo> lineInfos){
        Map<String,String> map = new HashMap<String,String>();
        BigDecimal totalWeight=new BigDecimal(0);
        for(OrderLineInfo line:lineInfos){
            String goodsHisId = line.getGoodsHisId();
            String goodsNum = line.getLineQuantity();
            OrderGoodsHisInfo goodsHisInfo = marketOrderMapper.findOrderGoodsHisById(goodsHisId);
            if(null==goodsHisInfo){
               // ("没有查询到相关的商品信息");
                map.put(ERROR,"没有查询到相关的商品信息");
                return map;
            }
            String specs = goodsHisInfo.getGoodsSpecifications();
            if(StringUtils.isBlank(specs)){
               // ("没有查询到商品规格信息");
                map.put(ERROR,"没有查询到商品规格信息");
                return map;
            }
            JSONArray array = JSONUtil.parseArray(specs);
            if(null==array || array.size()<1){
               // ("没有查询到商品规格信息");
                map.put(ERROR,"没有查询到商品规格信息");
                return map;
            }
            for(int i=0;i<array.size();i++){
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                JSONObject job = array.getJSONObject(i);
                // 得到 每个对象中的属性值
                if(job.get("id").equals(line.getSpecHisId())){
                    // 该对象中的id等于specHisId，就取出该对象中的重量值
                    Object weightObj = job.get("weight");
                    if(null==weightObj){
                       // ("商品重量信息不允许为空");
                        map.put(ERROR,"商品重量信息不允许为空");
                        return map;
                    }
                    String weight = String.valueOf(job.get("weight"));
                    totalWeight = totalWeight.add(new BigDecimal(goodsNum).multiply(new BigDecimal(weight)));
                    map.put("goods_totalWeight",totalWeight.toString());
                }
            }
        }
        // 1:25公斤以内（包含25公斤），2:25-50公斤（包含50公斤），3:50公斤以上
        int val = bigDecimalCompare(totalWeight,new BigDecimal("25"));
        if(val<1){
            // totalWeight 在25公斤以内（包含25公斤）
            map.put(SUCCESS,"1");
            return map;
        }
        int val2 = bigDecimalCompare(totalWeight,new BigDecimal("50"));
        if(val2<1){
            // totalWeight 25-50公斤（包含50公斤）
            map.put(SUCCESS,"2");
            return map;
        }
        // 否则的话，totalWeight就在50公斤以上
        map.put(SUCCESS,"3");

        return map;
    }

    /**
     * 六、计算商家需要支付的跑腿费用
     *      return map
     *          key为ERROR时，表示有错误信息
     *          key为SUCCESS时，表示跑腿费用计算正常
     */
    private Map<String,String> getPriceAsync(GetPriceModel model){
        Map<String,String> map = new HashMap<String,String>();
        if (model.getDis() <= 0){
            map.put(ERROR,"距离不能为空");
            return map;
        }
        map.put("dis",String.valueOf(model.getDis()));
        // 1：帮送，2：帮买，3：帮办     ;    曹操跑腿中的订单到曹操跑腿之后只会有帮送这一种情况
        if (model.getOrderType() != 1 ){
             map.put(ERROR,"订单类型取值：1/2/3，对于曹操来了的订单向曹操跑腿甩单而言，只会有“帮送（类型：1）”这一种类型");
             return map;
        }
        map.put("orderType",String.valueOf(model.getOrderType()));
        //  订单重量 1:25公斤以内（包含25公斤），2:25-50公斤（包含50公斤），3:50公斤以上
        if (model.getWeight() != 1 && model.getWeight() != 2 && model.getWeight() != 3){
            map.put(ERROR,"订单重量取值：1/2/3；1:25公斤以内（包含25公斤），2:25-50公斤（包含50公斤），3:50公斤以上");
            return map;
        }
        if (model.getAgentId() <= 0){
            map.put(ERROR,"代理商信息不能为空");
            return map;
        }
        if (model.getMemberId() <= 0){
            map.put(ERROR,"下单会员信息不能为空；请检查门店是否绑定了曹操跑腿中的发单账号");
            return map;
        }
        //计算价格
        BigDecimal price = new BigDecimal("0");
        //优惠后金额
        BigDecimal payPrice = new BigDecimal("0");
        //特殊加价金额
        BigDecimal specialPrice = new BigDecimal("0");
        //时间段加价金额
        BigDecimal timePrice = new BigDecimal("0");
        //起步价
        BigDecimal startPrice = new BigDecimal("0");
        //配送里程加价金额
        BigDecimal kmPrice = new BigDecimal("0");
        //重量加价
        BigDecimal weightPrice = new BigDecimal("0");
        //帮代办项目价格
        BigDecimal itemPrice = new BigDecimal("0");
        //是否使用优惠券
        BigDecimal couponAmount = new BigDecimal("0");
        BigDecimal couponUse = new BigDecimal("0");
        Date couponDate = DateUtils.getDate();
        int couponId = 0;
        // 计算发曹操跑腿的原始价格
//        String ccptOriginalMoney = "";

        // 帮送
        DisPriceModel disPrice = null;
        //是否需要走代理商默认价格
        boolean isAgentPrice = false;
        //确定计价方案
        if(model.getOrderType()==1){
            //会员是否有vip价格
            log.info("ccJedis是否连接 ：：：：：  "+ccJedis.isConnected());
            ccJedis.select(23);
            String redisObj = ccJedis.hget("vipPrice",model.getMemberId()+"-1");
            log.info("帮送vip价格-- 408行---->"+redisObj);
            if(StringUtils.isNotBlank(redisObj)){
                disPrice = JSONUtil.toBean(redisObj, DisPriceModel.class);
                if (disPrice == null){
                    //vip计价失败，采用代理商默认价格
                    isAgentPrice = true;
                }else{
                    // 使用vip价格进行计价
                    JSONObject redisJsonObject = JSONUtil.parseObj(redisObj);
                    List<DisPrice> kmDisPriceConfigList = new ArrayList<>();
                    JSONArray jsonArray  = redisJsonObject.getJSONArray("price");
                    DisPrice[] prices = new DisPrice[jsonArray.size()];
                    for (int i=0;i<jsonArray.size();i++){
                        DisPrice pr = new DisPrice();
                        pr.setStart(Integer.parseInt(String.valueOf(jsonArray.getJSONObject(i).get("Start"))));
                        pr.setEnd(Integer.parseInt(String.valueOf(jsonArray.getJSONObject(i).get("End"))));
                        pr.setPrice(new BigDecimal(String.valueOf(jsonArray.getJSONObject(i).get("Price"))));
                        prices[i] = pr;
                    }
                    disPrice.setPrice(prices);
                }
            }else{
                isAgentPrice = true;
            }
            // 是否需要代理商默认价格
            if (isAgentPrice){
                // 加载代理商配置
                ccJedis.select(23);
                String agentConfig1 = ccJedis.hget("agentConfig",model.getAgentId()+"-1");
                log.info("代理商的配置:423行--->  "+agentConfig1);
                if(StringUtils.isBlank(agentConfig1)){
                    map.put(ERROR,"价格计算失败，请稍后重度");
                    return map;
                }
                log.info("帮我送，走代理商默认价格，agentPrice："+agentConfig1);
                JSONObject jobj = JSONUtil.parseObj(agentConfig1);
                JSONArray jsonArray = jobj.getJSONArray("price");

                disPrice = JSONUtil.toBean(jobj,DisPriceModel.class);
                log.info("439行----》   "+disPrice.getPrice().length);
                disPrice.setPrice(null);
                DisPrice[] prices = new DisPrice[jsonArray.size()];
                for (int i=0;i<jsonArray.size();i++){
                    DisPrice pr = new DisPrice();
                    pr.setStart(Integer.parseInt(String.valueOf(jsonArray.getJSONObject(i).get("Start"))));
                    pr.setEnd(Integer.parseInt(String.valueOf(jsonArray.getJSONObject(i).get("End"))));
                    pr.setPrice(new BigDecimal(String.valueOf(jsonArray.getJSONObject(i).get("Price"))));
                    prices[i] = pr;
                }
                log.info("prices[0].getEnd()--445行->  "+prices[0].getEnd());
                disPrice.setPrice(prices);
            }
        }
        //计价方案是否确定
        if (disPrice == null){
            log.info("未能确定计价方案");
            map.put(ERROR,"未能确定计价方案");
            return map;
        }else{
            //处理距离，转换成km并向上取整
            int disKM = model.getDis() / 1000;
            if (model.getDis() % 1000 > 0){
                disKM++;
            }
            if (disKM <= 0){
                disKM = 1;
            }
            //起步价
            price = price.add(disPrice.getStartPrice());
            startPrice = disPrice.getStartPrice();
            //是否超出最大公里
            if (disKM > disPrice.getBeyondKm()){
                BigDecimal m = (new BigDecimal(disKM).subtract(new BigDecimal( disPrice.getBeyondKm()))).multiply(new BigDecimal(disPrice.getBeyondPrice()));
                price = price.add(m);
                kmPrice = kmPrice.add(m);
            }
            log.info("区间价格配置--2022-04-12夜---》   "+JSONUtil.toJsonStr(disPrice.getPrice()));
            for (DisPrice item : disPrice.getPrice()){
                if(item.getEnd()==0){continue;}
                if (disKM > item.getStart()){
                    int i = item.getEnd() - item.getStart();
                    if (i <= 0){
                        map.put(ERROR,"价格设置异常");
                        return map;
                    }
                    if (disKM < item.getEnd()){
                        i = disKM-item.getStart();
                    }
                    if (i < 1){
                        i = 1;
                    }
                    price = price.add(item.getPrice().multiply(new BigDecimal(i)));
                    kmPrice = kmPrice.add(item.getPrice().multiply(new BigDecimal(i)));
                }
            }
        }
        // 获取vip时间段加价
        boolean isAgentTime = true;
        ccJedis.select(23);
        String vipTimeStr = ccJedis.hget("vipPrice", model.getMemberId() + "-3");
        log.info("获取到的vip时间段加价---477行--->   "+vipTimeStr);
        if(null != vipTimeStr && StringUtils.isNotBlank(vipTimeStr)){
            JSONObject jobj = JSONUtil.parseObj(vipTimeStr);
            JSONArray jsonArray = jobj.getJSONArray("Times");
            VipTimePrice vipTime = JSONUtil.toBean(jobj,VipTimePrice.class);

            if(null!=vipTime && null != jsonArray){
                List<TimeItem> timeItems = new ArrayList<>();
                for(int i=0;i<jsonArray.size();i++){
                    TimeItem time = new TimeItem();
                    time.setStartTime(Integer.parseInt(jsonArray.getJSONObject(i).get("StartTime").toString()));
                    time.setEndTime(Integer.parseInt(jsonArray.getJSONObject(i).get("EndTime").toString()));
                    time.setPrice(new BigDecimal(jsonArray.getJSONObject(i).get("Price").toString()));
                    timeItems.add(time);
                }
                vipTime.setTimes(timeItems);
                if(vipTime.getIsOpenTime()==1){
                    //开启时间段加价
                    if(vipTime.getTimes().size()>0){
                        isAgentTime = false;
                        //是否预约单
                        Date nowDt = DateUtils.getDate();
                        int h = nowDt.getHours();
                        for(TimeItem item : vipTime.getTimes()){
                            if (h >= item.getStartTime() && h < item.getEndTime()){
                                price = price.add(item.getPrice());
                                timePrice = item.getPrice();
                                break;
                            }
                            //首尾相等代表全天加价
                            if (item.getStartTime() == item.getEndTime()){
                                price = price.add(item.getPrice());
                                timePrice = item.getPrice();
                                break;
                            }else if(item.getStartTime() > item.getEndTime()){
                                if (h < item.getEndTime() || h >= item.getStartTime()){
                                    price = price.add(item.getPrice());
                                    timePrice = item.getPrice();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        //获取代理商配置信息，是否开启特殊加价，是否开启时间段加价
        ccJedis.select(23);
        String agentConfig = String.valueOf(ccJedis.hget("agentConfig",model.getAgentId()+"-3"));
        log.info("代理商配置信息-----514行--->   "+agentConfig);
        if (null != agentConfig && StringUtils.isNotBlank(agentConfig)){
            JSONObject jobj = JSONUtil.parseObj(agentConfig);
            JSONArray jsonArray = jobj.getJSONArray("Times");
            SpecialModel special = JSONUtil.toBean(jobj,SpecialModel.class);
            if (special == null){
                log.info("代理商配置信息（加价设置）解析失败！");
                log.info("配置信息："+agentConfig);
            }else{
                SpecialTimes[] specialTimes = new SpecialTimes[jsonArray.size()];
                for(int i=0;i<jsonArray.size();i++){
                    SpecialTimes time = new SpecialTimes();
                    time.setStartTime(Integer.parseInt(jsonArray.getJSONObject(i).get("StartTime").toString()));
                    time.setEndTime(Integer.parseInt(jsonArray.getJSONObject(i).get("EndTime").toString()));
                    time.setPrice(jsonArray.getJSONObject(i).get("Price").toString());
                    specialTimes[i] = time;
                }
                special.setTimes(specialTimes);
                if (special.getIsOpenSpecial() == 1){
                    // 开启特殊加价
                    price = price.add(new BigDecimal(special.getSpecialPrice()));
                    specialPrice = new BigDecimal(special.getSpecialPrice());
                }
                //是否需要代理商时间段加价
                if (isAgentTime && special.getIsOpenTime() == 1){
                    //开启时间段加价
                    if (special.getTimes().length > 0){
                        Date ndt = DateUtils.getDate();
                        int h = ndt.getHours();
                        for(SpecialTimes item : special.getTimes()){
                            if (h >= item.getStartTime() && h < item.getEndTime()){
                                price = price.add(new BigDecimal(item.getPrice()));
                                timePrice = new BigDecimal(item.getPrice());
                                break;
                            }
                            //首位相等代表全天加价
                            if (item.getStartTime() == item.getEndTime()){
                                price = price.add(new BigDecimal(item.getPrice()));
                                timePrice = new BigDecimal(item.getPrice());
                                break;
                            }else if(item.getStartTime() > item.getEndTime()){
                                if (h < item.getEndTime() || h >= item.getStartTime()){
                                    price = price.add(new BigDecimal(item.getPrice()));
                                    timePrice = new BigDecimal(item.getPrice());
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        // 重量加价
        List<WeightPrice> wp = new ArrayList<WeightPrice>();
        ccJedis.select(23);
        String wpStr = String.valueOf(ccJedis.hget("agentConfig", model.getAgentId() + "-12"));
        log.info("重量加价------559行--->   "+wpStr);
        try{
            wp = JSONUtil.toList(JSONUtil.parseArray(wpStr),WeightPrice.class);
        }catch (Exception ex){
            log.info("重量加价，json转换失败；"+ex.getMessage());
        }
        if (wp.size() > 0){
            for (WeightPrice item : wp){
                if (item.id == model.getWeight()){
                    price = price.add(new BigDecimal(item.getPrice()));
                    weightPrice = new BigDecimal(item.getPrice());
                }
            }
        }else{
            if (model.getWeight() == 2){
                price = price.add(new BigDecimal(20));
                weightPrice = new BigDecimal(20);
            }else if (model.getWeight() == 3){
                price = price.add(new BigDecimal(50));
                weightPrice = new BigDecimal(50);
            }
        }

        //配送工具加价
        BigDecimal dispatchingMoney = new BigDecimal(0);
        if (model.getDispatchingType() == 2){
            //非电动车配送需要加价
            //获取代理商设置的加价
            ccJedis.select(23);
            String dispatchingStr = String.valueOf(ccJedis.hget("agentConfig", model.getAgentId() + "-10"));
            log.info("代理商设置的加价:-------589行-->  "+dispatchingStr);
            if(StringUtils.isBlank(dispatchingStr)){
                map.put(ERROR,"当前区域暂不支持除电动车之外的其它工具配送");
                return map;
            }
            dispatchingMoney = new BigDecimal(dispatchingStr);
            if (bigDecimalCompare(dispatchingMoney,new BigDecimal(0))<1){
                map.put(ERROR,"当前区域暂不支持其它工具配送");
                return map;
            }
            price = price.add(dispatchingMoney);
        }
        price = price.add(model.getRaisePrice());
        price = price.add(model.getImprest());
        log.info("优惠前计算的金额：" + String.valueOf(price));
        /**
         * 检测是否使用优惠券
         *      如果有优惠券就返回优惠券的信息
         *      关于优惠券需要再次核对（切记 ！！！！！！）
         *
         */
        log.info(String.format("findCouponIdByMemberIdAndAgentId(%s, %s, %s)", model.getAgentId(), model.getMemberId(), couponDate));
        Map<String,Object> couponMap = findCouponIdByMemberIdAndAgentId(model.getAgentId(),model.getMemberId(),couponDate,String.valueOf(price));
        couponMap.keySet().forEach(log::info);
        couponMap.values().forEach(e->log.info(e.toString()));
        couponMap.values().forEach(e->log.info(String.valueOf(e.toString())));
        if(couponMap.containsKey(SUCCESS)){
            // 优惠过后 向跑腿实际支付的跑腿费用
//            ccptOriginalMoney = couponMap.get(ACTUAL_CCPT_PRICE);
            log.info("707 line");
            // Timestamp useEndDate = (Timestamp) couponMap.get("useEndDate");
            // String useEndDateString = String.valueOf(useEndDate);
            try {
                if (couponMap.containsKey("couponMap.containsKey(\"money\") && ") && ObjectUtils.isNotEmpty(couponMap.get("useEndDate"))) {
                    couponDate = DateUtils.str2Date(String.valueOf(couponMap.get("useEndDate")),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                }
                if (couponMap.containsKey("money") && ObjectUtils.isNotEmpty("money")) {
                    couponAmount = new BigDecimal(String.valueOf(couponMap.get("money")));
                }
                if (couponMap.containsKey("useMoney") && ObjectUtils.isNotEmpty("useMoney")) {
                    couponUse = new BigDecimal(String.valueOf(couponMap.get("useMoney")));
                }
                if (couponMap.containsKey("sid") && ObjectUtils.isNotEmpty("sid")) {
                    couponId = Integer.parseInt(String.valueOf(couponMap.get("sid")));
                }
            } catch (Exception e) {
                log.error("优惠券couponDate错误，{}", e.getMessage());
            }
            map.put("couponAmount",String.valueOf(couponAmount));
            map.put("couponId",String.valueOf(couponId));
            map.put("couponUse",String.valueOf(couponUse));
        }
        //优惠
        if(bigDecimalCompare(couponAmount,new BigDecimal(0))==1  && bigDecimalCompare(price,couponUse)>-1){
            // 使用优惠券
            payPrice = price.subtract(couponAmount);
            log.info("优惠后计算的金额：" + String.valueOf(payPrice));
        }else{
            // 未使用优惠券
            payPrice = price;
        }
        if (bigDecimalCompare(payPrice,new BigDecimal(0))<1){
            payPrice = new BigDecimal(0.01);
        }
        log.info("最终计算的金额：" + String.valueOf(payPrice));
        model.setTruePrice(payPrice);
//        这一部分先不做
//          是否开启分站数据修正
//        redisUtil.setDataBase(0);
//        String amendSet = String.valueOf(redisUtil.hget("amendOpenSet",String.valueOf(model.getAgentId())));
//        if (StringUtils.isNotBlank(amendSet)){
//            //查询分站设置
//            redisUtil.setDataBase(0);
//            String adis = String.valueOf(redisUtil.hget("amendSet", String.valueOf(model.getMemberId())));
//            log.info( "数据修正（米）：" + adis);
//            if(StringUtils.isNotBlank(adis)){
//                int amdis = Integer.parseInt(adis);
//                model.setAmendDis(amdis);
//                model.setTruePrice(payPrice);
//                model.setDis(model.getDis()+amdis);
//                //重新计算价格
//                return GetPriceAmend(model);
//            }
//        }
        //价格标识
        if (StringUtils.isBlank(model.getPriceId())){
            model.setPriceId(MD5Util.MD5Encode(UUID.randomUUID().toString(),null));
        }
        // 处理返回数据
        List<Object> list = new ArrayList<Object>();
        if(bigDecimalCompare(price,new BigDecimal(0))==1){
            // price >0
            ReturnData re = new ReturnData();
            re.setName("订单金额");
            re.setPrice(price.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if(bigDecimalCompare(startPrice,new BigDecimal(0))==1){
            // startPrice >0
            ReturnData re = new ReturnData();
            re.setName("起步价");
            re.setPrice(startPrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
            map.put("startPrice",re.getPrice());
        }
        if(bigDecimalCompare(kmPrice,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("超公里计价");
            re.setPrice(kmPrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if (bigDecimalCompare(specialPrice,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("特殊天气加价");
            re.setPrice(specialPrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
            map.put("specialPrice",re.getPrice());
        }
        if(bigDecimalCompare(timePrice,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("时间段加价");
            re.setPrice(timePrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
            map.put("timePrice",re.getPrice());
        }
        if (bigDecimalCompare(weightPrice,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("重量加价");
            re.setPrice(weightPrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if (bigDecimalCompare(itemPrice,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("项目价格");
            re.setPrice(itemPrice.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if (bigDecimalCompare(model.getRaisePrice(),new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("加价金额");
            re.setPrice(model.getRaisePrice().setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if (bigDecimalCompare(model.getImprest(),new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("预付金");
            re.setPrice(model.getImprest().setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }
        if (bigDecimalCompare(dispatchingMoney,new BigDecimal("0"))==1){
            ReturnData re = new ReturnData();
            re.setName("配送工具加价");
            re.setPrice(dispatchingMoney.setScale(2, RoundingMode.HALF_UP).toString());
            list.add(re);
        }

        ReturnData yhje = new ReturnData();
        yhje.setName("优惠金额");
        yhje.setPrice(couponAmount.setScale(2, RoundingMode.HALF_UP).toString());
        list.add(yhje);

        ReturnData zfje = new ReturnData();
        zfje.setName("支付金额");
        zfje.setPrice(payPrice.setScale(2, RoundingMode.HALF_UP).toString());
        list.add(zfje);

        JSONObject target1 = new JSONObject();
        target1.putOpt("couponDate",DateUtils.date2Str(couponDate,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        target1.putOpt("startPrice",startPrice.toString());
        target1.putOpt("kmPrice",kmPrice.toString());
        target1.putOpt("specialPrice",specialPrice.toString());
        target1.putOpt("timePrice",timePrice.toString());
        target1.putOpt("weightPrice",weightPrice.toString());
        map.put("weightPrice",weightPrice.toString());
        target1.putOpt("price",price.toString());
        target1.putOpt("couponAmount",couponAmount.toString());
        target1.putOpt("payPrice",payPrice.toString());
        target1.putOpt("raisePrice",model.getRaisePrice().toString());
        target1.putOpt("imprest",model.getImprest().toString());
        target1.putOpt("dispatchingMoney",dispatchingMoney.toString());
        map.put("dispatchingMoney",dispatchingMoney.toString());
        target1.putOpt("amendDis",String.valueOf(model.getAmendDis()));
        target1.putOpt("truePrice",model.getTruePrice().toString());

        JSONObject target = new JSONObject();
        target.putOpt("price",price);
        target.putOpt("priceId",model.getPriceId());
        target.putOpt("agentId",model.getAgentId());
        target.putOpt("specialPrice",specialPrice.toString());
        target.putOpt("timePrice",timePrice.toString());
        target.putOpt("payPrice",payPrice.toString());
        target.putOpt("priceData", JSONUtil.toJsonStr(list));
        //存入redis
        ccJedis.select(22);
//        ccJedis.set("price:" + model.getPriceId(),JSONUtil.toJsonStr(target1),20*60);
        ccJedis.set("price:" + model.getPriceId(),JSONUtil.toJsonStr(target1));
        // 设置过期时间
        ccJedis.expire("price:" + model.getPriceId(),20*60);
        map.put(SUCCESS,JSONUtil.toJsonStr(target));
        map.put(SUCCESS+"target",JSONUtil.toJsonStr(target1));
        map.put(SUCCESS+"couponId",String.valueOf(couponId));
        map.put("payPrice",payPrice.toString());
        return map;
    }

    /**
     * 七、构建向跑腿订单表插入的数据模型
     */
    private Map<String, String> createOrderModel(Map<String,String> map){
        log.info("map----807行----》  "+map.toString());
        Map<String,String> returnMap = new HashMap<String,String>();
        String jsonStr = map.get(SUCCESS);
        log.info("810----->jsonStr = "+jsonStr);
        // {"agentId":252,"timePrice":"0","price":8.8,"payPrice":"8.8","priceData":"[{\"price\":\"8.80\",\"name\":\"订单金额\"},{\"price\":\"7.80\",\"name\":\"起步价\"},{\"price\":\"1.00\",\"name\":\"超公里计价\"},{\"price\":\"0.00\",\"name\":\"优惠金额\"},{\"price\":\"8.80\",\"name\":\"支付金额\"}]","priceId":"dc8f47d3995208dddb72f75c0bb4d8f5","specialPrice":"0"}
        JSONObject jObj = JSONUtil.parseObj(jsonStr);
        log.info("jObj--------813行---》   "+jObj.toString());

        String jsTargetSttr = map.get(SUCCESS+"target");
        JSONObject jTargetObj = JSONUtil.parseObj(jsTargetSttr);
        log.info("jTargetObj--------817行---》   "+jTargetObj.toString());
        returnMap.put("price",jTargetObj.get("truePrice").toString());
        returnMap.put("kmPrice",jTargetObj.get("kmPrice").toString());
        returnMap.put("couponId",map.get(SUCCESS+"couponId"));
        returnMap.put("couponAmount",jTargetObj.get("couponAmount").toString());
        returnMap.put("amendDis",String.valueOf(0));
        returnMap.put("orderSource",String.valueOf(153));
        returnMap.put("payAmount",jTargetObj.get("payPrice").toString());
        returnMap.put("orderAmount",jTargetObj.get("payPrice").toString());
        returnMap.put("specialPrice",jTargetObj.get("specialPrice").toString());
        returnMap.put("startPrice",jTargetObj.get("startPrice").toString());
        returnMap.put("timePrice",jTargetObj.get("timePrice").toString());
        returnMap.put("weightPrice",jTargetObj.get("weightPrice").toString());
        // 收货人地址id没有，默认0
        returnMap.put("receiptSid",String.valueOf(0));
        // 发货人地址id没有，默认0
        returnMap.put("sendAddrSid",String.valueOf(0));
        returnMap.put("dispatchingMoney",jTargetObj.get("dispatchingMoney").toString());
        returnMap.put("dispatchingType",String.valueOf(1));
        returnMap.put("amendAmount",String.valueOf(0));

        return returnMap;
    }
    /**
     * 八、创建CreateOrderModel数据模型
     */
    private Map<String,String> createCcOrder(OrderBaseInfo marketOrder,Map<String,String> params){
        Map<String,String> map = new HashMap<>();
        //检查当前区域是否正常营业
        ccJedis.select(5);
        String agentWorkStr = ccJedis.hget("agentWork", marketOrder.getPtAgentId());
        log.info("检查当前区域是否正常营业--> 793行-->   "+agentWorkStr);
        if (null != agentWorkStr && StringUtils.isNotBlank(agentWorkStr)){
            JSONObject agentWork = JSONUtil.parseObj(agentWorkStr);
            int agstatus = Integer.parseInt(agentWork.get("status").toString());
            if (agstatus != 1){
                String agmsg = agentWork.get("message").toString();
                map.put(ERROR,agmsg);
                return map;
            }
        }
        int memberId = Integer.parseInt(params.get("memberId"));
        if(memberId<1){
            map.put(ERROR,"发单会员id不能为空");
            return map;
        }
        BigDecimal orderAmount = new BigDecimal(params.get("orderAmount"));
        if(bigDecimalCompare(orderAmount,new BigDecimal(0))<1){
            map.put(ERROR,"订单支付金额必须大于0");
            return map;
        }
        int orderDis = Integer.parseInt(params.get("orderDis"));
        if(orderDis<=0){
            map.put(ERROR,"距离不能为空");
            return map;
        }
        // 检查下单用户的状态
        int memberStatus = ccptMapper.findMemberStatus(Integer.parseInt(params.get("memberId")));
        if(memberStatus!=0){
            map.put(ERROR,"用户状态异常，请联系管理员");
            return map;
        }
        //获取代理商配置信息（超时罚款）
        AgentTimeOut agentTimeOut = null;
        int isOpenPenalty = 0, takeTime = 0, takePenalty = 0, sendTime = 0, sendPenalty = 0;//是否开启超时罚款，取货时间限制，取货超时罚款
        if(Integer.parseInt(params.get("orderType")) == 1){
            //获取redis中代理商配置的超时罚款信息
            ccJedis.select(23);
            String agentConfig = String.valueOf(ccJedis.hget("agentConfig", params.get("agentId")+ "-5"));
            log.info("代理商配置的超时罚款信息---831行-->  "+agentConfig);
            JSONObject jobj = JSONUtil.parseObj(agentConfig);
            JSONArray jsonArray = jobj.getJSONArray("SendPenalty");


            if(null != agentConfig && StringUtils.isNotBlank(agentConfig)){
                // 反序列化
                agentTimeOut  = JSONUtil.toBean(jobj,AgentTimeOut.class);
                if (null != agentTimeOut){
                    List<SendpenaltyItem> sendpenaltyItems = JSONUtil.toList(jsonArray,SendpenaltyItem.class);
                    if(null!=sendpenaltyItems && sendpenaltyItems.size()>0){
                        agentTimeOut.setSendPenalty(sendpenaltyItems);
                    }
                    //是否开启超时罚款
                    isOpenPenalty = agentTimeOut.getIsOpenPenalty();
                    if (isOpenPenalty == 1){
                        //取货超时时间限制，单位：分钟
                        takeTime = agentTimeOut.getTakeTime();
                        //取货超时罚款金额，单位：元
                        takePenalty = agentTimeOut.getTakePenalty();
                        //处理送货超时时间
                        if (agentTimeOut.getSendPenalty() != null && agentTimeOut.getSendPenalty().size() > 0){
                            for(SendpenaltyItem item:agentTimeOut.getSendPenalty()){
                                BigDecimal dis1 = new BigDecimal(params.get("orderDis")).divide(new BigDecimal(1000));
                                if(bigDecimalCompare(dis1,new BigDecimal(item.getStart()))>-1 && bigDecimalCompare(dis1,new BigDecimal(item.getEnd()))<0){
                                    //送货超时时间限制，单位：分钟
                                    sendTime = item.getTimeOut();
                                    //送货超时罚款金额，单位：元
                                    sendPenalty = item.getPrice();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        //发件人和收件人是否新用户————————————这里暂时不判断

        //获取发单用户所在用户组的结算方案

        Map<String,Integer> brokerageMap =  ccptMapper.findBrokerageByAgentIdAndMemberId(Integer.parseInt(params.get("agentId")),Integer.parseInt(params.get("memberId")));
        int brokerage_sid =0;
        if(null!=brokerageMap && brokerageMap.containsKey("brokerageId")){
            brokerage_sid = brokerageMap.get("brokerageId");
        }
        //生成订单号
        String orderno = getOrderNumber();
        /**  修正信息暂时不做
         * //是否有修正信息
         * int amendDis = priceInfo.amendDis;
         * decimal truePrice = priceInfo.truePrice;
            */
        log.info("params------940--> "+params.toString());
        CcOrder ccOrder = new CcOrder();
        //订单实体
        ccOrder.setBrokerageSid(brokerage_sid);
        ccOrder.setStat(0);
        ccOrder.setAgentSid(Integer.parseInt(params.get("agentId")));
        ccOrder.setAmount(new BigDecimal(params.get("price")));
        ccOrder.setBeyondPrice(new BigDecimal(params.get("kmPrice")));
        ccOrder.setCallbackUrl("");
        ccOrder.setCouponSid(Integer.parseInt(params.get("couponId")));
        ccOrder.setCreateDate(DateUtils.getDate());
        ccOrder.setDiscounts(new BigDecimal(params.get("couponAmount")));
        ccOrder.setGoodsType("其它");
        ccOrder.setGoodsWeight(params.get("goodsWeight"));
        ccOrder.setImprest(new BigDecimal(params.get("imprest")));
        ccOrder.setIsOpenPenalty(isOpenPenalty ==1 ? true : false);
        ccOrder.setTakePenalty((byte)takePenalty);
        ccOrder.setTakeTime(null);
        ccOrder.setTableNo("");
        ccOrder.setTakeTimeout((short)takeTime);
        ccOrder.setIsScheduling(false);
        ccOrder.setSchedulingTime(null);
        ccOrder.setMemberSid(Integer.parseInt(params.get("memberId")));
        ccOrder.setOrderDis(Integer.parseInt(params.get("orderDis")) + Integer.parseInt(params.get("amendDis")));
        ccOrder.setOrderNo(orderno);
        ccOrder.setOrderSource((byte) Integer.parseInt(params.get("orderSource")));

        ccOrder.setOrderType((byte)Integer.parseInt(params.get("orderType")));
        ccOrder.setPayAmount(new BigDecimal(params.get("payAmount")));
        ccOrder.setPaySerno("");

        ccOrder.setPushCount((byte)0);
        ccOrder.setRaisePrice(new BigDecimal(params.get("raisePrice")));
        ccOrder.setReadyTime(null);
        ccOrder.setReceiptAddr(params.get("receiptAddr"));
        ccOrder.setReceiptAddrAoi(params.get("receiptAddrAoi"));
        ccOrder.setReceiptAddrHouse(params.get("receiptAddrHouse"));
        ccOrder.setReceiptLat(params.get("receiptLat"));
        ccOrder.setReceiptLon(params.get("receiptLon"));
        ccOrder.setReceiptMobile(params.get("receiptMobile"));
        ccOrder.setReceiptName(params.get("receiptName"));
        ccOrder.setReceiveTime(null);
        ccOrder.setRemark(params.get("remark"));
        ccOrder.setRewardMoney(new BigDecimal("0"));
        ccOrder.setSendAddr(params.get("sendAddr"));
        ccOrder.setSendAddrAoi(params.get("sendAddrAoi"));
        ccOrder.setSendAddrHouse(StringUtils.isBlank(params.get("sendAddrHouse"))? "":params.get("sendAddrHouse"));
        ccOrder.setSendLat(params.get("sendLat"));
        ccOrder.setSendLon(params.get("sendLon"));
        ccOrder.setSendMobile(params.get("sendMobile"));
        ccOrder.setSendName(params.get("sendName"));
        ccOrder.setSendPenalty((byte)sendPenalty);
        ccOrder.setSendTime(null);
        ccOrder.setSendTimeout((byte)sendTime);
        ccOrder.setSpecialPrice(new BigDecimal(params.get("specialPrice")));
        ccOrder.setStaffSid(0);
        ccOrder.setStartPrice(new BigDecimal(params.get("startPrice")));
        ccOrder.setThirdPartyNo(params.get("marketOrderNo"));
        ccOrder.setTimePrice(new BigDecimal(params.get("timePrice")));
        ccOrder.setWeightPrice(new BigDecimal(params.get("weightPrice")));
        ccOrder.setLockVersion(1);
        ccOrder.setReceiptAddrSid(Integer.parseInt(params.get("receiptSid")));
        ccOrder.setSendAddrSid(Integer.parseInt(params.get("sendAddrSid")));
        ccOrder.setDispatchingMoney(new BigDecimal(params.get("dispatchingMoney")));
        ccOrder.setDispatchingType(Integer.parseInt(params.get("dispatchingType")));
        ccOrder.setAmendDis(Integer.parseInt(params.get("amendDis")));
        ccOrder.setAmendAmount(new BigDecimal(params.get("amendAmount")));
        log.info("groupSid-----1009行----》   "+params.get("groupSid"));
        ccOrder.setGroupSid(Integer.parseInt(StringUtils.isBlank(params.get("groupId"))?"0":params.get("groupId")));
        ccOrder.setRemark("曹操来了（订单号："+marketOrder.getOrderNo()+"）；"+(StringUtils.isBlank(params.get("remark")) ? "" : params.get("remark")));
        ccOrder.setPayTime(DateUtils.getDate());
        ccOrder.setDisAmount(new BigDecimal(params.get("disAmount")));
        try {
            ccOrder.setCancelTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("1753-01-01 00:00:00.000"));
        } catch (ParseException e) {
           log.info("取消日期解析错误！");
        }
        /**
         * 向发单客户扣款
         * 需要处理
         */
        Map<String,Object> memberMap = ccptMapper.findMemberForBalance(ccOrder.getMemberSid());
        if(null==memberMap){
            map.put(ERROR,"发单账号异常，发单失败！");
            return map;
        }

        BigDecimal balance = (BigDecimal) memberMap.get("balance");
        if(null==balance){
            map.put(ERROR,"没有检测到发单账号的余额信息，无法发单！");
            return map;
        }
        if(bigDecimalCompare(balance,ccOrder.getPayAmount())<0){
            map.put(ERROR,"发单账号余额不足，无法完成发单！");
            return map;
        }
        // 创建订单时，订单状态为0 等扣过发单商户的钱之后，把这个值改为1
        ccOrder.setOrderStatus((byte)1);
        ccOrder.setPayStatus((byte)1);
        ccOrder.setPayTime(DateUtils.getDate());
        ccOrder.setPayWay((byte)6);
        // 将ccOrder写入数据库;返回cc_order表中的主键sid
        int ccOrderId = ccptMapper.insertCcOrder(ccOrder);
        if(ccOrderId<1){
            map.put(ERROR,"写入跑腿订单数据库失败！");
            return map;
        }
        // 可以正常发单并且发单成功，进行扣款；计算剩下的余额
        BigDecimal surplusBalance =  balance.subtract(ccOrder.getPayAmount());
        String surplusBalanceStr = surplusBalance.setScale(2,BigDecimal.ROUND_HALF_UP).toString();
        // 更新余额
        ccptMapper.updateBalanceBySid(surplusBalanceStr,ccOrder.getMemberSid());
        map.put(SUCCESS,"写入跑腿订单数据库成功！");
        log.info("订单对象---》  "+ccOrder.toString());
        map.put("ccOrderId",String.valueOf(ccOrder.getSid()));
        return  map;
    }

    /**
     * 九、查询跑腿订单
     */
    private CcOrder findCcptOrderById(int orderId){
        CcOrder ccOrder =ccptMapper.findCcptOrderById(orderId);
        return ccOrder;
    }
    /**
     * 十、如果使用了优惠券就更新优惠券的状态
     */
    private Map<String,String> updateCounpon(Map<String,String> params){
        Map<String,String> reMap = new HashMap<String,String>();
        //是否使用优惠券
        int couponId = Integer.parseInt(params.get("couponId"));
        BigDecimal couponAmount = new BigDecimal(params.get("couponAmount"));
        //更新优惠券使用状态
        if(couponId>0 && bigDecimalCompare(couponAmount,new BigDecimal(0))==1){
            ccptMapper.checkCouponById(DateUtils.getDate(),couponId);
            //  //添加优惠券核销记录
            CouponUse couponUse = new CouponUse();
            couponUse.setAgentSid(Integer.parseInt(params.get("agentId")));
            couponUse.setCouponSid(0);
            couponUse.setCouponUserSid(couponId);
            couponUse.setCreateDate(DateUtils.getDate());
            couponUse.setMoney(new BigDecimal(params.get("couponMoney")));
            couponUse.setOrderNo(params.get("ccOrderNo"));
            couponUse.setUseDate(DateUtils.getDate());
            couponUse.setUseMoney(new BigDecimal(params.get("disCounts")));
            couponUse.setUserSid(Integer.parseInt(params.get("memberId")));
            couponUse.setOrderSid(Integer.parseInt(params.get("ccOrderId")));
            ccptMapper.insertCouponUse(couponUse);
            reMap.put(SUCCESS,"添加优惠券核销记录成功！");
        }
        return  reMap;
    }
    /**
     * 十、将跑腿系统中的订单写入redis

    private Map<String,String> insertRedis(CcOrder order){
        Map<String,String> map = new HashMap<String,String>();

        map.put(SUCCESS,"写入数据库成功！");
        return map;
    }
     */
    /**
     * 十、新订单推送
     */
    private Map<String,String> newOrderPush(CcOrder order){
        Map<String,String> reMap = new HashMap<String,String>();
        //推送范围
        int dis = 0;
        int pushType = 1;
        AgentPushSet pushSet = null;
        ccJedis.select(23);
        String agentConfig =  ccJedis.hget("agentConfig",order.getAgentSid()+"-4");
        log.info("代理商配置的新订单的推送范围--1007行--->   "+agentConfig);
        // string agentConfig = RedisHelper.HashGet("agentConfig", order.AgentSid + "-4", 23).ToString();
        if (StringUtils.isBlank(agentConfig)){
            //未能查询到代理商的推送设置
            log.info("新订单推送时未能解析推送设置，取系统默认的推送范围，agentid："+order.getAgentSid()+" orderid："+order.getSid());
        }else{
            pushSet = JSONUtil.toBean(agentConfig,AgentPushSet.class);
            if (pushSet == null){
                log.info("新订单推送时未能解析推送设置，取系统默认的推送范围，agentid："+order.getAgentSid()+" orderid："+order.getSid());
            }else{
                if (pushSet.getPushType()== 1){
                    //按距离
                    dis = pushSet.getDis1();
                }else{
                    //全城推送
                    // dis = ServiceCenter.GetInstance<IConfigService>().AppSettings.PushAllCity;
                    // 经向鹏飞确认，全城推送默认20公里;
                    // 需要转换为米(20*1000)
                    dis = 20000;
                    pushType = 2;
                }
            }
        }
        if (pushSet == null){
            // dis = ServiceCenter.GetInstance<IConfigService>().AppSettings.PushScope;
            // 这里需要获取配置信息
            // 经向鹏飞确认，PushScope是从配置文件里面取的，值为：3公里
            // 需要转换为米(3*1000)
            dis = 3;
        }
        // 获取附近的骑士
//        找保垒要接口获取nearby,nearby是一个数组
//        StackExchange.Redis.GeoRadiusResult[] nearby = new StackExchange.Redis.GeoRadiusResult[] { };
        List<GeoRadiusResponse> nearby = new ArrayList<GeoRadiusResponse>();
        //骑手推送别名集合
        List<String> pushNames = new ArrayList<String>();
        String staffids = "";
        //骑手推送别名集合（小于500米）
        List<String> sldPush = new ArrayList<String>();
        //驻店骑士推送别名
        List<String> signIns = new ArrayList<String>();
        String saddr = "";
        double sdis = 0;
        //查询发单客户有没有驻店骑士，驻店骑士每天需要签到，至少一个骑士签到成功才能优先推送
        ccJedis.select(10);
        String signInStaffStr = ccJedis.get("signInStaff:"+order.getMemberSid());
        log.info("查询发单客户有没有驻店骑士---1053行-->   "+signInStaffStr);
        if(null != signInStaffStr && StringUtils.isNotBlank(signInStaffStr)){
            staffids = signInStaffStr;
            if (signInStaffStr.contains(",")){
                String[] ids = signInStaffStr.split(",");
                signIns = Arrays.asList(ids);
            }else{
                signIns.add(signInStaffStr);
            }
            log.info("新订单推送 订单号："+order.getOrderNo()+" 驻店骑士"+signIns.size()+"  "+staffids+" 不在查询附近骑士");
        }
        int isResident = signIns.size();
        //获取平台抽成比例
        BigDecimal rate = new BigDecimal("0");
        ccJedis.select(23);
        String r = ccJedis.hget("agentConfig", String.valueOf(order.getAgentSid()));
        log.info("平台抽成----1069行--->   "+r);
        if (null!=r && StringUtils.isNotBlank(r)){
            rate = new BigDecimal(r);
        }
        BigDecimal companyMoney = (order.getPayAmount().add(order.getDiscounts()).subtract(order.getRaisePrice())).multiply(rate);
        //获取订单补贴
        BigDecimal subsidy = new BigDecimal(0);
        ccJedis.select(23);
        String subsidyStr = ccJedis.hget("agentConfig", order.getAgentSid() + "-7");
        log.info("订单补贴----1078行-->   "+subsidyStr);
//        String subsidyStr = RedisHelper.HashGet("agentConfig", order.AgentSid + "-7", 23).ToString();
        if (null != subsidyStr && StringUtils.isNotBlank(subsidyStr)){
            try{
                AgentSubsidyConfig asc = JSONUtil.toBean(subsidyStr,AgentSubsidyConfig.class);
                if (asc != null && asc.getStatus() == 1 && asc.getResidue() > 0){
                    subsidy = asc.getMoney();
                }
            }catch (Exception e){
                subsidy = new BigDecimal(0);
            }
        }
        //是否开启分站骑士计提设置
        OrderPushRateConfig opr = new OrderPushRateConfig();
        ccJedis.select(3);

        String opSet = ccJedis.hget("orderPushSet", String.valueOf(order.getAgentSid()));
        log.info("分站是否开启骑士计提设置----1095行-->   "+opSet);
        if (null != opSet && StringUtils.isNotBlank(opSet)){
            //获取分站的骑士计提设置
            ccJedis.select(3);
            String oprStr = ccJedis.hget("orderPushRate", String.valueOf(order.getAgentSid()));
            log.info("分站的骑士计提设置---1100行--->  "+oprStr);
            if (oprStr!=null && StringUtils.isNotBlank(oprStr)){
//                opr = JsonHelper.JsonToEntity<OrderPushRateConfig>(oprStr);
                opr = JSONUtil.toBean(oprStr,OrderPushRateConfig.class);
                if (opr.Status != 1) {
                    opr = new OrderPushRateConfig();
                }
            }
        }

        //给骑手添加新订单缓存 未接订单在骑手的新订单列表里最多存放48小时
        JSONObject neworder = new JSONObject();
        neworder.putOpt("a",order.getSid());
        neworder.putOpt("b",order.getImprest());
        neworder.putOpt("c",1);
        neworder.putOpt("d",order.getGoodsType());
        neworder.putOpt("e",Double.parseDouble(String.valueOf(order.getPayAmount().add(order.getDiscounts()))));
        neworder.putOpt("f",String.valueOf(order.getSendAddrAoi()+order.getSendAddrHouse()));
        neworder.putOpt("j",StringUtils.isBlank(order.getSendLon()) ? order.getReceiptLon() : order.getSendLon());
        neworder.putOpt("k",StringUtils.isBlank(order.getSendLat()) ? order.getReceiptLat() : order.getSendLat());
        neworder.putOpt("l",order.getReceiptAddrAoi()+order.getReceiptAddrHouse());
        neworder.putOpt("m",Double.parseDouble(String.valueOf(order.getTimePrice())));
        neworder.putOpt("n",Double.parseDouble(String.valueOf(order.getSpecialPrice())));
        neworder.putOpt("o",Double.parseDouble(String.valueOf(companyMoney)));
        neworder.putOpt("agentId",order.getAgentSid());
        neworder.putOpt("subsidy",Double.parseDouble(String.valueOf(subsidy)));
        neworder.putOpt("newUser",0);
        neworder.putOpt("gid",order.getBrokerageSid());
        neworder.putOpt("memberSid",order.getMemberSid());
        neworder.putOpt("isResident",isResident);
        neworder.putOpt("pushRate",null==opr.getPush1()?0:Double.parseDouble(String.valueOf(opr.getPush1())));
        neworder.putOpt("r",order.getOrderDis());
        neworder.putOpt("u",order.getRaisePrice());
        neworder.putOpt("v","");
        neworder.putOpt("x",order.getGoodsWeight());
        neworder.putOpt("y",order.getSendTimeout());
        Date now = DateUtils.getDate();
        // 当前时间加1秒
        now.setTime(now.getTime()+1000);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        neworder.putOpt("z",df.format(now));
        // 新订单详情
        int orderSrouce = 153;
        String remark = orderSrouce + " 客户备注：" + order.getRemark();
       // int takeTimeOut = 0;
//        int TakeTimeOut = ServiceCenter.GetInstance<IConfigService>().AppSettings.TakeTimeOut;
//         这里需要查询配置项：TakeTimeOut
        // 经向鹏飞确认，TakeTimeOut的值是从配置文件appsettings.json里面取的，值为20分钟
        int takeTimeOut = 20;
       //  //是否配置了取货超时罚款
        ccJedis.select(23);
        String takep = ccJedis.hget("agentConfig", order.getAgentSid() + "-9");
        log.info("是否配置了取货超时罚款-->1152行--> "+takep);
        if (null!= takep && StringUtils.isNotBlank(takep)){
            JSONObject takepModel = JSONUtil.parseObj(takep);
            if (null!=takepModel){
                takeTimeOut = Integer.parseInt(String.valueOf(takepModel.get("TakeTime")));
            }
        }
        JSONObject neworderInfo = new JSONObject();
        neworderInfo.putOpt("PushRate",null==opr.getPush1() ? 0 : Double.parseDouble(String.valueOf(opr.getPush1())));
        neworderInfo.putOpt("OrderImg",order.getCallbackUrl());
        neworderInfo.putOpt("IsResident",isResident);
        neworderInfo.putOpt("Gid",order.getBrokerageId());
        neworderInfo.putOpt("NewUser",order.getStat());
        neworderInfo.putOpt("TableNo",order.getTableNo());
        neworderInfo.putOpt("CallbackUrl",order.getCallbackUrl());
        neworderInfo.putOpt("ThirdPartyNo",order.getThirdPartyNo());
        neworderInfo.putOpt("MemberSid",order.getMemberSid());
        neworderInfo.putOpt("StaffSid",order.getStaffSid());
        neworderInfo.putOpt("OrderStatus",order.getOrderStatus());
        neworderInfo.putOpt("AgentSid",order.getAgentSid());
        neworderInfo.putOpt("Sid",order.getSid());
        neworderInfo.putOpt("OrderNo",order.getOrderNo());
        neworderInfo.putOpt("OrderType",order.getOrderType());
        neworderInfo.putOpt("GoodsType",order.getGoodsType());
        neworderInfo.putOpt("PayAmount",order.getPayAmount());
        neworderInfo.putOpt("SendAddrAoi",order.getSendAddrAoi());
        neworderInfo.putOpt("SendAddrHouse",order.getSendAddrHouse());
        neworderInfo.putOpt("SendName",order.getSendName());
        neworderInfo.putOpt("SendMobile",order.getSendMobile());
        neworderInfo.putOpt("SendLon",order.getSendLon());
        neworderInfo.putOpt("SendLat",order.getSendLat());
        neworderInfo.putOpt("ReceiptAddrAoi",order.getReceiptAddrAoi());
        neworderInfo.putOpt("ReceiptAddrHouse",order.getReceiptAddrHouse());
        neworderInfo.putOpt("ReceiptName",order.getReceiptName());
        neworderInfo.putOpt("ReceiptMobile",order.getReceiptMobile());
        neworderInfo.putOpt("ReceiptLon",order.getReceiptLon());
        neworderInfo.putOpt("ReceiptLat",order.getReceiptLat());
        neworderInfo.putOpt("OrderDis",order.getOrderDis());
        neworderInfo.putOpt("Discounts",order.getDiscounts());
        neworderInfo.putOpt("Imprest",order.getImprest());
        neworderInfo.putOpt("RaisePrice",order.getRaisePrice());
        neworderInfo.putOpt("SpecialPrice",order.getSpecialPrice());
        neworderInfo.putOpt("TimePrice",order.getTimePrice());
        neworderInfo.putOpt("CompanyMoney",companyMoney);
        neworderInfo.putOpt("Subsidy",subsidy);
        neworderInfo.putOpt("OS",orderSrouce);
        neworderInfo.putOpt("PayTime",order.getPayTime());
        neworderInfo.putOpt("Remark",order.getRemark());
        neworderInfo.putOpt("GoodsWeight",order.getGoodsWeight());
        neworderInfo.putOpt("ReadyTimeOut",order.getTakeTimeout());
        neworderInfo.putOpt("TakePenalty",order.getTakePenalty());
        neworderInfo.putOpt("TakeTimeOut",takeTimeOut);
        neworderInfo.putOpt("SendTimeout",order.getSendTimeout());
        neworderInfo.putOpt("SendPenalty",order.getSendPenalty());
        neworderInfo.putOpt("AmendPrice",order.getAmendAmount());
        neworderInfo.putOpt("SchedulingTime","");
        neworderInfo.putOpt("ReceiveTime",null==order.getReceiveTime() ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm").format(order.getReceiveTime()));
        neworderInfo.putOpt("ReadyTime",null==order.getReadyTime() ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm").format(order.getReadyTime()));
        neworderInfo.putOpt("TakeTime",null==order.getTakeTime() ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm").format(order.getTakeTime()));
        //添加新订单
        ccJedis.select(25);
        ccJedis.set("newOrderInfo:"+order.getSid(),JSONUtil.toJsonStr(neworderInfo));
        //添加新订单到hash
        ccJedis.select(25);
        ccJedis.hset("newOrder",String.valueOf(order.getSid()),String.valueOf(dis));
        //筛选骑手，以订单的发货地坐标为中心，dis为半径，查询骑手
        String lon = StringUtils.isBlank(order.getSendLon()) ? order.getReceiptLon() : order.getSendLon();
        lon = StringUtils.isBlank(lon) ? "0" : lon;
        String lat = StringUtils.isBlank(order.getSendLat()) ? order.getReceiptLat() : order.getSendLat();
        lat = StringUtils.isBlank(lat) ? "0" : lat;
        if (isResident <= 0){
            ccJedis.select(27);
            nearby = ccJedis.georadius("nearbyStaff",Double.parseDouble(lon),Double.parseDouble(lat),dis,GeoUnit.M);
            log.info("查询附近的骑士---1225行-->  "+nearby);
            log.info("新订单推送 订单号："+order.getOrderNo()+" 在"+dis+"米范围内查询到"+nearby.size()+"个骑手");
        }else{
            //驻店推送
            String x2 = "";
            for (String item : signIns){
                ccJedis.select(23);
                String staffConfig = ccJedis.hget("staffConfig",item);
                log.info("查询驻店骑士-----1233行---->   "+staffConfig);
                if (null != staffConfig && StringUtils.isNotBlank(staffConfig)){
                    StaffConfigModel staff = null;
                    try{
                        staff = JSONUtil.toBean(staffConfig,StaffConfigModel.class);
                        if (staff == null || staff.getAgentSid() <= 0 || staff.getStatus() != 0) {
                            x2 += "name：" + staff.getName() + ",id:" + staff.getSid() + ", phone:" + staff.getMobile() + "," +
                                    "agentId:" + staff.getAgentSid() + "-" + staff.getAgentName() + " canTake：" + staff.getCanTakeOrder() + ",nowTake：" + staff.getNowTakeOrder() + " workStatus：" + staff.getWorkStatus() + " 别名：" + staff.getPushName() + " status：" + staff.getStatus();
                        }
                    }catch (Exception ex){
                        log.info("解析驻店骑士失败："+ex.getMessage());
                        continue;
                    }
                    if (staff != null && (staff.getNowTakeOrder() < staff.getCanTakeOrder() || staff.getCanTakeOrder() == 0)
                            && StringUtils.isNotBlank(staff.getPushName())
                            && staff.getStatus() == 0 && staff.getWorkStatus() == 1){
                        //处理临时移除的情况
                        if (staff.getResidentUid() != order.getMemberSid()){continue;}
                        //处理重复签到的情况
                        if (pushNames.contains(staff.getPushName())) {continue;}
                        //取出推送别名
                        pushNames.add(staff.getPushName());
                        //给骑手添加新订单缓存
                        ccJedis.select(25);
                        ccJedis.set("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),JSONUtil.toJsonStr(neworder));
                        ccJedis.expire("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),12*60*60);
                    }
                }
            }
            log.info("驻店推送过滤："+x2);
        }
        if (nearby.size() > 0){
            int i = 0;
            int disqu = 0;
            int dissong = 0;
            //订单归属代理商是否开通顺路单匹配
            ccJedis.select(5);
            String sld = ccJedis.hget("sldSet", String.valueOf(order.getAgentSid()));
            log.info("顺路单---1270行--->  "+sld);
            //var sld = RedisHelper.HashGet("sldSet", order.AgentSid.ToString(), 5).ToString();
            if(null != sld && StringUtils.isNotBlank(sld)){
                //取货地点匹配半径
                JSONObject qu = JSONUtil.parseObj(sld);
                if (qu != null){
                    disqu = Integer.parseInt(String.valueOf(qu.get("disStart")));
                    dissong = Integer.parseInt(String.valueOf(qu.get("disEnd")));
                    log.info("代理商id："+order.getAgentSid()+",顺路单匹配起点半径："+disqu+", 终点半径："+dissong);
                }
            }
            String x1 = "-";
            for (GeoRadiusResponse item : nearby){
                i++;
                ccJedis.select(23);
                String staffConfig = ccJedis.hget("staffConfig", String.valueOf(item));
                if (null != staffConfig && StringUtils.isNotBlank(staffConfig)){
                    StaffConfigModel staff = null;
                    try{
                        staff = JSONUtil.toBean(staffConfig,StaffConfigModel.class);
                        if (staff != null && staff.getAgentSid() > 0 && staff.getStatus() == 0){
                            x1 += "name："+staff.getName()+",id:"+staff.getSid()+", phone:"+staff.getMobile()+" dis:"+item.getDistance()+" " +
                                    "agentId:"+staff.getAgentSid()+"-"+staff.getAgentName()+" canTake："+staff.getCanTakeOrder()+",nowTake："+staff.getNowTakeOrder()+"" +
                                    " workStatus："+staff.getWorkStatus()+" 别名："+staff.getPushName()+" status："+staff.getStatus();
                        }
                    }catch (Exception ex){
                        log.info("骑士信息解析出错--line 1282  -- "+ex.getMessage());
                        continue;
                    }
                    if (staff != null && (staff.getNowTakeOrder() < staff.getCanTakeOrder() || staff.getCanTakeOrder() == 0)
                            && StringUtils.isNotBlank(staff.getPushName()) && staff.getStatus() == 0){
                        if (staff.getWorkStatus() != 1){continue;}
                        //是否黑名单
                        ccJedis.select(10);
                        String bl = ccJedis.hget("blackList:" + order.getMemberSid(), String.valueOf(staff.getSid()));
                        log.info("是否黑名单-----1306行---->   "+bl);
                        if (null != bl && StringUtils.isNotBlank(bl)){continue;}
                        //订单不共享的处理
                        ccJedis.select(5);
                        String oos = ccJedis.get("orderShareOff");
                        log.info("订单不共享处理----1311行---->  "+oos);
                        if (null!= oos && StringUtils.isNotBlank(oos)){
                            String[] ooss = oos.split(",");
                            int socount = 0;
                            for (String tt : ooss){
                                if (String.valueOf(order.getAgentSid()).equals(tt) && !String.valueOf(staff.getAgentSid()).equals(tt)){
                                    socount++;
                                    break;
                                }
                            }
                            if (socount > 0){ continue; }
                        }
                        //顺路单匹配
                        if (disqu > 0 && item.getDistance() < disqu){
                            //骑手当前位置距离订单发货地小于设置的距离
                            //获取该骑手当前的进行中订单
                            ccJedis.select(24);
                            List<String> sending = getKeys("sendingOrder:"+staff.getSid()+"-*");
                            log.info("1329行---->   "+sending);
                            if (sending.size() > 0){
                                //循环当前骑手的配送中订单
                                for (String tt : sending){
                                    JSONObject sendingOrder = JSONUtil.parseObj(tt);
                                    if (null != sendingOrder){
                                        String slon = String.valueOf(sendingOrder.get("ReceiptLon"));
                                        String slat = String.valueOf(sendingOrder.get("ReceiptLat"));
                                        //测量收货地址半径
                                        double lat1 = Double.parseDouble(StringUtils.isBlank(slat)?"0":slat);
                                        double lon1 = Double.parseDouble(StringUtils.isBlank(slon)?"0":slon);
                                        sdis = getDistance(lat1, lon1, Double.parseDouble(StringUtils.isBlank(order.getReceiptLat())?"0":order.getReceiptLat()),
                                                Double.parseDouble(StringUtils.isBlank(order.getReceiptLon())?"0":order.getReceiptLon()));
                                        if (sdis < dissong){
                                            //添加至顺路单
                                            sldPush.add(staff.getPushName());
                                            //顺路单地址信息
                                            saddr = String.valueOf(sendingOrder.get("ReceiptAddrAoi"));
                                            //给骑手添加新订单缓存
                                            ccJedis.select(25);
                                            ccJedis.set("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),JSONUtil.toJsonStr(neworder));
                                            ccJedis.expire("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),12*60*60);
                                            //跳出当前配送中订单循环
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        //取出推送别名
                        pushNames.add(staff.getPushName());
                        //取出骑士id
                        staffids += staff.getSid();
                        staffids += ",";
                        if (sldPush.size() < 1){
                            //给骑手添加新订单缓存
                            ccJedis.select(25);
                            ccJedis.set("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),JSONUtil.toJsonStr(neworder));
                            ccJedis.expire("staffNewOrder:"+staff.getSid()+"-"+order.getSid(),12*60*60);
                            // RedisHelper.StringSet($"staffNewOrder:{staff.Sid}-{order.Sid}", neworder.ToJson(), ts, 25);
                        }
                    }
                }
                //最多推送300个
                if (i >= 500){ break;}
            }
            //去掉最后一个逗号
            if (staffids.contains(",")){
                staffids = staffids.substring(0,staffids.length()-1);
            }
            log.info("推送骑士ids: "+staffids);
        }
        //推送
        //顺路单
        if (sldPush.size() > 0){
            JSONObject target = new JSONObject();
            target.putOpt("Push1",opr.getPush1());
            target.putOpt("Push2",opr.getPush2());
            target.putOpt("pushCount",0);
            target.putOpt("orderId",order.getSid());
            target.putOpt("dis",dis);
            target.putOpt("pushType",pushType);
            target.putOpt("SendLon",lon);
            target.putOpt("SendLat",lat);
            target.putOpt("order",JSONUtil.toJsonStr(neworder));
            target.putOpt("agentId",order.getAgentSid());
            target.putOpt("DispatchingType",order.getDispatchingType());
            target.putOpt("MemberSid",order.getMemberSid());
            JSONObject neworder1 = new JSONObject();
            neworder1.putOpt("a",Integer.parseInt(String.valueOf(order.getSid())));
            neworder1.putOpt("b",0);
            neworder1.putOpt("c",Integer.parseInt(String.valueOf(order.getOrderType())));
            neworder1.putOpt("d",order.getGoodsType());
            neworder1.putOpt("e",Double.parseDouble(String.valueOf(order.getPayAmount().add(order.getDiscounts()))));
            neworder1.putOpt("f",order.getSendAddrAoi() + order.getSendAddrHouse());
            neworder1.putOpt("j",StringUtils.isBlank(order.getSendLon()) ? order.getReceiptLon() : order.getSendLon());
            neworder1.putOpt("k",StringUtils.isBlank(order.getSendLat()) ? order.getReceiptLat() : order.getSendLat());
            neworder1.putOpt("l",order.getReceiptAddrAoi() + order.getReceiptAddrHouse());
            neworder1.putOpt("m",Double.parseDouble(String.valueOf(order.getTimePrice())));
            neworder1.putOpt("n",Double.parseDouble(String.valueOf(order.getSpecialPrice())));
            neworder1.putOpt("o",Double.parseDouble(String.valueOf(companyMoney)));
            neworder1.putOpt("agentId",Integer.parseInt(String.valueOf(order.getAgentSid())));
            neworder1.putOpt("subsidy",Double.parseDouble(String.valueOf(subsidy)));
            neworder1.putOpt("newUser",0);
            neworder1.putOpt("pushRate",StringUtils.isBlank(String.valueOf(opr.getPush1()))?0:Double.parseDouble(String.valueOf(opr.getPush1())));
            neworder1.putOpt("gid",Integer.parseInt(String.valueOf(order.getBrokerageSid())));
            neworder1.putOpt("os",Integer.parseInt(String.valueOf(order.getOrderSource())));
            neworder1.putOpt("r",Integer.parseInt(String.valueOf(order.getOrderDis())));
            neworder1.putOpt("u",order.getRaisePrice());
            neworder1.putOpt("v","");
            neworder1.putOpt("x",order.getGoodsWeight());
            neworder1.putOpt("y",order.getSendTimeout());
            // 当前时间加1秒
            neworder1.putOpt("z",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtils.getDate().getTime()+1000));
            neworder1.putOpt("sdis",sdis);
            neworder1.putOpt("saddr",saddr);
            //优先推顺路单
            log.info("优先推送顺路单，人数："+sldPush.size()+"-"+JSONUtil.toJsonStr(sldPush));
            orderPush(sldPush,21,neworder1);
            //添加下次推送到mq
//            nextPushSLD(JSONUtil.toJsonStr(target),"nextPushSLD");
        }else{
            if (pushNames.size() > 0){
                orderPush(pushNames, 1, "newOrder");
            }
            JSONObject target = new JSONObject();
            target.putOpt("Push1",opr.getPush1());
            target.putOpt("Push2",opr.getPush2());
            target.putOpt("pushCount",1);
            target.putOpt("orderId",order.getSid());
            target.putOpt("dis",dis);
            target.putOpt("pushType",pushType);
            target.putOpt("SendLon",lon);
            target.putOpt("SendLat",lat);
            target.putOpt("order",JSONUtil.toJsonStr(neworder));
            target.putOpt("agentId",order.getAgentSid());
            target.putOpt("DispatchingType",order.getDispatchingType());
            target.putOpt("MemberSid",order.getMemberSid());

            //添加下次推送到mq
            if (signIns.size() > 0) {
//                nextPushSLD(JSONUtil.toJsonStr(target),"nextPushSLD");
            }else {
//                nextPushSLD(JSONUtil.toJsonStr(target),"nextPush");
            }
        }
        //添加推送记录
        if (null != staffids && StringUtils.isNotBlank(staffids)){
            try{
                //添加订单推送记录 更新修正信息
                ccptMapper.insertRabbitMqRecord(order.getSid(),order.getAgentSid(),dis,staffids);
            }catch (Exception ex){
                log.info("添加推送记录出错："+ ex.getMessage());
            }
        }

        reMap.put(SUCCESS,"推送成功");
        return reMap;

    }

    /**
     * 推送(极光推送)
     *      新订单推送
     */
    private void orderPush(List<String> pushNames, int code, Object data){
        try{
            //根据别名进行推送
//            获取PushSound获取声音配置
            ccJedis.select(5);
            String body = ccJedis.get("wechatPayTitle");
            log.info("1480行------->   "+body);
            if (StringUtils.isBlank(body)){ body = "曹操跑腿"; }
            Map<String, String> extras = new HashMap<String,String>();
            extras.put("code",String.valueOf(code));
            extras.put("data",JSONUtil.toJsonStr(data));
            extras.put("title",body);
            extras.put("builder_id",String.valueOf(1));
            extras.put("large_icon","http://img.ccpt.xyz/app/875c2ca7-d83c-45a7-9a6f-e8ace57d3e99.jpg");
            extras.put("time_to_live",String.valueOf(60));
            extras.put("apns_production",String.valueOf(true));
            JiGuangPushUtil.jpushAll(extras,"您有新订单 点击抢单",pushNames.toArray(new String[0]));
        }catch (Exception e){
            log.info("调用极光推送失败："+e.getMessage());
        }
    }

//    /**
//     * rabbitMQ
//     * 下次推送 nextPushSLD
//     */
//    public void nextPushSLD(String message, String nextPushType) {
//        Connection connection = null;
//        Channel channel = null;
//        try {
//            connection = factory.newConnection();
//            log.info("rabbitMQ连接成功");
//            channel = connection.createChannel();
//            channel.basicPublish("", nextPushType, null, message.getBytes(StandardCharsets.UTF_8));
//        } catch (Exception e) {
//            log.info("添加到rabbitMQ下次推送出错：" + e.getMessage());
//        } finally {
//            try {
//                if (channel != null) channel.close();
//                if (connection != null) connection.close();
//            } catch (IOException | TimeoutException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    public List<String> getKeys(String pattern){
        String keyPattern = "*" + pattern + "*";
        Set<String> setkeys = ccJedis.keys(keyPattern);
        log.info("1520行-------->   "+setkeys);
        if(null==setkeys || setkeys.size()<1){
            return null;
        }
        List<String> resultList = new ArrayList<>(setkeys);
        return resultList;
    }
    /// <summary>
    /// 获取两点（坐标）之间的直线距离
    /// </summary>
    /// <param name="lat1"></param>
    /// <param name="lng1"></param>
    /// <param name="lat2"></param>
    /// <param name="lng2"></param>
    /// <returns></returns>
    public  double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = Rad(lat1);
        double radLat2 = Rad(lat2);
        double a = radLat1 - radLat2;
        double b = Rad(lng1) - Rad(lng2);
        double s = 2 * Math.sin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137; //地球半径 km
        s = Math.round(s * 10000) / 10;
        return s;
    }
    private static double Rad(double d){
        return d * Math.PI / 180.0;
    }
    /**
     * 根据时间生成订单号
     */
    public static String getOrderNumber(){
       /* String num = DateTime.Now.ToString("yyMMddHHmmssfff") + Number(3, true);//yyyyMMddHHmmssms
        return fix + num + Number(2, true).ToString();*/
        return   DateUtils.date2Str(new Date(), DateUtils.yymmddhhmmssSSSSS.get())+number(3,true);
    }
    /// 生成随机数字
    /// </summary>
    /// <param name="Length">生成长度</param>
    /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
    /// <returns></returns>
    public static String number(int Length, boolean sleep){
        if (sleep) {
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                log.info("生成随机数异常！");
            }
        }
        String result = "";
        Random random = new Random();
        for (int i = 0; i < Length; i++){
            result += String.valueOf(random.nextInt(10));
        }
        return result;
    }

    public Map<String,Object>  findCouponIdByMemberIdAndAgentId(int ccptAgentId,int ccptMemberId,Date couponDate,String price){
        // couponMember里面的key值：sid,money,userMoney
        Map<String,Object> couponMember = ccptMapper.findCouponByCondation(ccptMemberId,ccptAgentId,couponDate,price);
        /*Map<String, String> couponMember = new HashMap<String, String>() {{
            put("money", "5.00");
            put("useMoney", "6.00");
            put("userSid", "279496");
            put("useEndDate", "2022-04-03 14:44:12.873");
            put("sid", "419323");
            put("status", "1");
        }};*/
        log.info("1590行------》   "+couponMember);
        /*BigDecimal couponAmount = new BigDecimal(0);
        BigDecimal couponUse = new BigDecimal(0);
        BigDecimal originalPriceDecimal = new BigDecimal(originalPrice);*/
        BigDecimal actualCcptPrice = new BigDecimal("0");
        if (couponMember != null){
            log.info("查询到发单会员的目前可用的优惠券信息；会员id(cc_member表中的id)="+ccptMemberId);
            /*couponAmount = new BigDecimal(couponMember.get("money"));
            couponUse = new BigDecimal(couponMember.get("useMoney"));
            // couponAmount 先和0比较；
            int f1 = bigDecimalCompare(couponAmount,new BigDecimal(0));
            int f2 = bigDecimalCompare(originalPriceDecimal,couponUse);
            if (f1==1 && f2==1){
                // subtract 减
                actualCcptPrice = originalPriceDecimal.subtract(couponAmount);
                log.info("优惠后的实际支付的跑腿费用：" + actualCcptPrice.toString());
            }*/
            if (bigDecimalCompare(actualCcptPrice,new BigDecimal("0"))<1 ){
                /* update date 2022-03-03 by chechen
                * 初始化BigDecimal时用String类型，Double类型转换会精度丢失，例如
                * new BigDecimal("0.01") = 0.01
                * new BigDecimal(0.01) = 0.01000000000000000020816681711721685132943093776702880859375 */
                actualCcptPrice = new BigDecimal("0.01");
            }
            log.info("最终计算出需要支付的跑腿费payPrice=" + actualCcptPrice);
            couponMember.put("success","有可用的优惠券信息");
        }else{
            couponMember = new HashMap<>();
            couponMember.put("error","没有查询到发单会员的目前可用的优惠券信息");
        }
        // 没有可以使用的优惠券就返回0
        couponMember.put("actualCcptPrice",String.valueOf(actualCcptPrice));
        return couponMember;
    }
    /**
     * 用到的工具方法：两个BigDecimal比较大小
     *      flag = -1,表示big1小于big2；
     *         flag = 0,表示big1等于big2；
     *         flag = 1,表示big1大于big2；
     */
    private int bigDecimalCompare(BigDecimal big1,BigDecimal big2){
        int flag = big1.compareTo(big2);
        return flag;
    }

    // 内部类
    class ReturnData{
        private String name;
        private String price;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }
    }
    // 内部类
    class OrderPushRateConfig{
        public int AgentId ;
        public BigDecimal Push1 ;
        public BigDecimal Push2 ;
        public BigDecimal Push3 ;
        public int Status ; //0关闭，1开启

        public int getAgentId() {
            return AgentId;
        }

        public void setAgentId(int agentId) {
            AgentId = agentId;
        }

        public BigDecimal getPush1() {
            return Push1;
        }

        public void setPush1(BigDecimal push1) {
            Push1 = push1;
        }

        public BigDecimal getPush2() {
            return Push2;
        }

        public void setPush2(BigDecimal push2) {
            Push2 = push2;
        }

        public BigDecimal getPush3() {
            return Push3;
        }

        public void setPush3(BigDecimal push3) {
            Push3 = push3;
        }

        public int getStatus() {
            return Status;
        }

        public void setStatus(int status) {
            Status = status;
        }
    }
}
